package rahmath.sharif.docrypt;

import rahmath.sharif.docrypt.constant.DocryptConstants;
import rahmath.sharif.docrypt.util.AESCryptor;
import rahmath.sharif.docrypt.util.DocryptUtil;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;

public class CryptTextActivity extends Activity implements DocryptConstants {

	@TargetApi(11)
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_crypt_text);
		if (Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB) {
			getActionBar().setDisplayHomeAsUpEnabled(true);
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_crypt_text, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			NavUtils.navigateUpFromSameTask(this);
			return true;
		case R.id.help:
			Intent helpActivity = new Intent(this, HelpActivity.class);
			startActivity(helpActivity);
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	public void copyToClipboard(View view) {
		DocryptUtil.doCopy(this,R.id.editTextOutputText);
	}

	public void pasteFromClipboard(View view) {
		DocryptUtil.doPaste(this,R.id.editTextInputText);
	}

	public void encrypt(View view) {
		String password = ((EditText) findViewById(R.id.editTextPassword))
				.getText().toString();
		String inputText = ((EditText) findViewById(R.id.editTextInputText))
				.getText().toString();
		Docrypt docrypt = new Docrypt(true);
		docrypt.execute(password, inputText);
	}

	public void decrypt(View view) {
		String password = ((EditText) findViewById(R.id.editTextPassword))
				.getText().toString();
		String inputText = ((EditText) findViewById(R.id.editTextInputText))
				.getText().toString();
		Docrypt docrypt = new Docrypt(false);
		docrypt.execute(password, inputText);
	}

	private class Docrypt extends AsyncTask<String, Integer, String> {
		private boolean doEncrypt;

		public Docrypt(boolean doEncrypt) {
			this.doEncrypt = doEncrypt;
		}

		@Override
		protected String doInBackground(String... strings) {
			String outputText = null;
			if (doEncrypt) {
				outputText = AESCryptor.encrypt(256, strings[0], strings[1]);
			} else {
				outputText = AESCryptor.decrypt(256, strings[0], strings[1]);
			}
			return outputText;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			((EditText) findViewById(R.id.editTextOutputText)).setText(result);
		}
	}
}
